package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.ColorChooserUI;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class SingleChatClient extends JFrame implements Runnable{

	Socket socket = null;
	BufferedWriter send = null;
	BufferedReader receive =null;
	boolean threadFlag = false;
	StringBuilder data = new StringBuilder();
	int portNum = 4444;
	
	
	
	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JTextField serverIP;
	private JButton btnLogout;
	private JButton btnLogin;
	private JButton btnNewButton_2;
	private JTextField message;
	private JScrollPane scrollPane;
	private JTextPane result;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SingleChatClient frame = new SingleChatClient();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SingleChatClient() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent arg0) {
				serverDisconnect();
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.NORTH);
		contentPane.add(getPanel_1(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
		
		try {
			InetAddress ia = InetAddress.getLocalHost();
			setTitle("IP주소 : "+ia.getHostAddress()+ " port번호 : "+portNum);
			
		} catch (Exception e) {
			
		}
	}

	@Override
	public void run() {
		
		try{
		socket = new Socket(serverIP.getText(),portNum);
		
		OutputStream os = socket.getOutputStream();
		OutputStreamWriter osw= new OutputStreamWriter(os);
		send = new BufferedWriter(osw);
		
		InputStream is = socket.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		receive = new BufferedReader(isr);
		
		threadFlag = true;
		
			while (threadFlag) {
				String str = receive.readLine();
				if ("\tserverdown".equals(str)) {
					threadFlag = false;
					sendMsg(str);
					break;
				} else if ("\tkill".equals(str)) {
					threadFlag = false;
					break;
				} else {
					dataSet("수신 : " + str);
				}
			}
		
		dataSet("접속이 해제되었습니다.<br>");
		
		receive.close(); isr.close(); is.close();
		send.close(); osw.close(); os.close();
		socket.close();
		
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public void dataSet(String d){//JTextPane에 문자열을 추가하기 위해서
		data.append(d);//StringBuilder에 String을 추가
		data.append("<br/>");
		result.setText(data.toString());
	}
	
	public void serverConnect(){//접속버튼을 클릭하면 호출
		try {
			dataSet("서버에 접속 되었습니다.");
			Thread t = new Thread(this);
			t.start();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}
	
	public void serverDisconnect(){//접속해제버튼이나 JFrame의 종료버튼이 클릭되면
		threadFlag =false;
		try {
			send.write("\tkill");
			send.newLine();
			send.flush();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}

	public void sendMsg(String ms){
		try{
			send.write(ms);
			send.newLine();
			send.flush();
			dataSet("<font color = 'blue'> 나 :"+ms+"</font>");
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.add(getBtnLogout());
			panel.add(getServerIP());
			panel.add(getBtnLogin());
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getBtnNewButton_2(), BorderLayout.EAST);
			panel_1.add(getMessage(), BorderLayout.CENTER);
		}
		return panel_1;
	}
	private JTextField getServerIP() {
		if (serverIP == null) {
			serverIP = new JTextField();
			serverIP.setText("192.168.10.130");
			serverIP.setColumns(10);
		}
		return serverIP;
	}
	private JButton getBtnLogout() {
		if (btnLogout == null) {
			btnLogout = new JButton("접속해제");
			btnLogout.setEnabled(false);
			btnLogout.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					btnLogin.setEnabled(true);
					btnLogout.setEnabled(false);
					serverDisconnect();
				}
			});
		}
		return btnLogout;
	}
	private JButton getBtnLogin() {
		if (btnLogin == null) {
			btnLogin = new JButton("서버접속");
			btnLogin.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					btnLogin.setEnabled(false);
					btnLogout.setEnabled(true);
					serverConnect();
				}
			});
		}
		return btnLogin;
	}
	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("메시지전송");
			btnNewButton_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					String str = message.getText();
					sendMsg(str);
					message.setText("");
				}
			});
		}
		return btnNewButton_2;
	}
	private JTextField getMessage() {
		if (message == null) {
			message = new JTextField();
			message.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if(e.getKeyCode()==KeyEvent.VK_ENTER){
						String str = message.getText();
						sendMsg(str);
						message.setText("");
					}else if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
						message.setText("");
					}
				}
			});
			message.setColumns(10);
		}
		return message;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}
}
